package com.pine.manager.pineframework.trigger.impl;

import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysDictSaveOrUpdateRequest;
import com.pine.common.trigger.TriggerContext;
import com.pine.dao.pineframework.entity.SysDict;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.bo.SysDictBo;
import com.pine.manager.pineframework.query.SysDictQuery;
import com.pine.manager.pineframework.trigger.AbstractTriggerTemplateAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * <p>
 * 系统字典表新增或修改数据 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-08-16
 */
@Component
@Slf4j
public class SysDictSaveOrUpdateTrigger extends AbstractTriggerTemplateAdapter<SysDictSaveOrUpdateRequest, Boolean> {

    private boolean isSave;

    private SysDictBo oldSysDictBo;


    public SysDictSaveOrUpdateTrigger() {
        super(TriggerTypeEnum.SYS_DICT_SAVE_OR_UPDATE);
    }

    @Override
    protected void before(TriggerContext<SysDictSaveOrUpdateRequest> triggerContext) {
        // 获取请求参数
        SysDictSaveOrUpdateRequest request = triggerContext.getTriggerRequest();
        isSave = Objects.isNull(request.getId());

        // 尝试查询旧的字典数据
        SysDictQuery query = new SysDictQuery();
        query.setId(request.getId());
        if (isSave) {
            query.setCode(request.getCode());
        }

        oldSysDictBo = sysDictManager.getOne(query);

        // 校验
        if (isSave) {
            checkOnSave();
        } else {
            checkOnUpdate();
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    public Boolean trigger(TriggerContext<SysDictSaveOrUpdateRequest> triggerContext) {
        // 获取请求参数
        SysDictSaveOrUpdateRequest request = triggerContext.getTriggerRequest();

        // 转换为业务对象
        SysDictBo newSysDictBo = sysDictConvertor.saveRequestToEntityBo(request);

        // 转换为实体
        SysDict sysDict = sysDictConvertor.entityBoToEntity(newSysDictBo);

        // 新增
        if (isSave) {
            return sysDictManager.save(sysDict);
        }
        // 修改
        return sysDictManager.updateById(sysDict);
    }

    private void checkOnUpdate() {
        // 校验字典ID是否存在
        if (Objects.isNull(oldSysDictBo)) {
            throw new BusinessException(ExceptionCodeEnum.DICT_NOT_EXIST);
        }
    }

    private void checkOnSave() {
        // 校验字典编码是否重复
        if (Objects.nonNull(oldSysDictBo)) {
            throw new BusinessException(ExceptionCodeEnum.DICT_EXIST);
        }
    }
}
